package com.hunterai.service.impl;

import com.hunterai.dao.UserRepository;
import com.hunterai.dto.UserDTO;
import com.hunterai.entity.User;
import com.hunterai.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {

    private final UserRepository userRepository;

    @Autowired
    public UserServiceImpl(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    @Override
    public List<UserDTO> findAll() {
        return userRepository.findAll().stream()
                .map(this::convertToDTO)
                .collect(Collectors.toList());
    }

    @Override
    public Optional<UserDTO> findById(Long id) {
        return userRepository.findById(id).map(this::convertToDTO);
    }

    @Override
    public Optional<UserDTO> findByUserName(String userName) {
        return userRepository.findByUserName(userName).map(this::convertToDTO);
    }

    @Override
    public Optional<User> findUserEntityById(Long id) {
        return userRepository.findById(id);
    }

    @Override
    public UserDTO save(User user) {
        // 手机号唯一性校验
        if (user.getMobile() != null && !user.getMobile().isEmpty()) {
            Optional<User> exist = userRepository.findByMobile(user.getMobile());
            if (exist.isPresent() && (user.getId() == null || !exist.get().getId().equals(user.getId()))) {
                throw new RuntimeException("手机号已被使用");
            }
        }
        User savedUser = userRepository.save(user);
        return convertToDTO(savedUser);
    }

    @Override
    public void deleteById(Long id) {
        userRepository.deleteById(id);
    }

    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        dto.setId(user.getId());
        dto.setUserName(user.getUserName());
        dto.setEmail(user.getEmail());
        dto.setCreatedAt(user.getCreatedAt());
        dto.setLastLogin(user.getLastLogin());
        dto.setAvatar(user.getAvatar());
        dto.setNickName(user.getNickName());
        dto.setGender(user.getGender() != null ? user.getGender().name() : null);
        dto.setMobile(user.getMobile());
        return dto;
    }
}